<template>
  <div class="sheep-death-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>
    <!-- 顶部表单区 -->
    <el-card class="form-card" shadow="never">
      <el-form :model="form" label-width="90px" class="death-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="死亡日期" required>
              <el-date-picker v-model="form.DeathDate" type="date" placeholder="请选择死亡日期" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <el-input v-model="form.OrderNumber" placeholder="--" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 明细表格区 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="form.details" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="SheepEarNumber" label="羊只耳号" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.SheepEarNumber" placeholder="羊只耳号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DeathReason" label="死亡原因" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.DeathReason" placeholder="死亡原因" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Breed" label="品种" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Breed" placeholder="品种" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Gender" placeholder="请选择" size="small">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="ReproductiveStatus" label="状态" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.ReproductiveStatus" placeholder="繁殖状态" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Buildings" label="当前栋舍" width="100" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Buildings" placeholder="请选择栋舍" size="small">
              <el-option v-for="item in penList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="FieldId" label="当前栏位" width="100" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.FieldId" placeholder="请选择栏位" size="small">
              <el-option v-for="item in fieldList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="BirthDate" label="出生日期" width="120" align="center">
          <template #default="scope">
            <el-date-picker v-model="scope.row.BirthDate" type="date" placeholder="出生日期" size="small" value-format="YYYY-MM-DD" />
          </template>
        </el-table-column>
      </el-table>
      <el-button @click="addDetail" style="margin-top: 8px;">+ 增行</el-button>
      <el-button @click="removeDetail" style="margin-top: 8px; margin-left: 8px;">- 删行</el-button>
    </el-card>
    <!-- 合计区 -->
    <div class="summary-section">
      <span>合计：{{ form.details.length }}</span>
    </div>
    <!-- 备注区 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="form.Remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Sheep_BreedingWrite } from '@/utils/Interceptors'
import { useRoute, useRouter } from 'vue-router'

const penList = ref<any[]>([])
const fieldList = ref<any[]>([])

const form = reactive({
  DeathDate: '',
  OrderNumber: '',
  Remark: '',
   SheepEarNumber: '',
      DeathReason: '',
      Breed: '',
      Gender: '',
      ReproductiveStatus: '',
      Buildings: '',
      FieldId: '',
      BirthDate: '',
  details: [
    {
      SheepEarNumber: '',
      DeathReason: '',
      Breed: '',
      Gender: '',
      ReproductiveStatus: '',
      Buildings: '',
      FieldId: '',
      BirthDate: ''
    }
  ]
})

const addDetail = () => {
  form.details.push({
    SheepEarNumber: '',
    DeathReason: '',
    Breed: '',
    Gender: '',
    ReproductiveStatus: '',
    Buildings: '',
    FieldId: '',
    BirthDate: ''
  })
}
const removeDetail = () => {
  if (form.details.length > 1) {
    form.details.pop()
  }
}
const handleSave = async () => {
  try {
    const data = {
      DeathDate: form.DeathDate,
      SheepEarNumber: form.details[0].SheepEarNumber,
      DeathReason: form.details[0].DeathReason,
      Breed: form.details[0].Breed,
      Gender: form.details[0].Gender,
      ReproductiveStatus: form.details[0].ReproductiveStatus,
      Buildings: Number(form.details[0].Buildings),
      BirthDate: form.details[0].BirthDate,
      OrderNumber: form.OrderNumber,
      Remark: form.Remark,
      FieldId: form.details[0].FieldId,
      FieldName: (form.details[0] as any).FieldName
    }
    if ((form as any).CreatorId) {
      (data as any).CreatorId = (form as any).CreatorId
    }
    let res
    if (route.query.id) {
      // 编辑，调用更新接口
      res = await Sheep_BreedingWrite.put('/api/SheepDeath/update', { ...data, Id: route.query.id })
    } else {
      // 新增
      res = await Sheep_BreedingWrite.post('/api/SheepDeath/add', data)
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '保存成功')
      router.push('/SheepDeathView')
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error((e as any)?.response?.data?.msg || '请求失败')
  }
}
const handleCancel = () => {
  ElMessage.info('已撤销（示例）')
}
const fetchPenList = () => {
  Sheep_BreedingWrite.get('/api/Pen/List').then(res => {
    penList.value = res.data.data || []
  })
}
const fetchFieldList = () => {
          Sheep_BreedingWrite.get('/api/FieldManagement/GetFieldManagementIdName', { baseURL: 'http://localhost:5109' }).then(res => {
    fieldList.value = res.data.data || []
  })
}
const route = useRoute()
const router = useRouter()
onMounted(() => {
  fetchPenList()
  fetchFieldList()
  if (route.query.id) {
    // 编辑，拉取详情
    Sheep_BreedingWrite.get(`/api/SheepDeath/detail/${route.query.id}`).then(res => {
      if (res.data && res.data.code === 200) {
        form.DeathDate = res.data.data.DeathDate || ''
        form.OrderNumber = res.data.data.OrderNumber || ''
        form.Remark = res.data.data.Remark || ''
        form.details = [
          {
            SheepEarNumber: res.data.data.SheepEarNumber || '',
            DeathReason: res.data.data.DeathReason || '',
            Breed: res.data.data.Breed || '',
            Gender: res.data.data.Gender || '',
            ReproductiveStatus: res.data.data.ReproductiveStatus || '',
            Buildings: res.data.data.Buildings || '',
            FieldId: res.data.data.FieldId || '',
            BirthDate: res.data.data.BirthDate || ''
          }
        ]
      }
    })
  }
})
</script>

<style scoped>
.sheep-death-add-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}
.action-bar {
  margin-bottom: 16px;
}
.form-card {
  margin-bottom: 18px;
}
.death-form {
  padding: 12px 0;
}
.table-card {
  margin-bottom: 12px;
}
.summary-section {
  margin: 12px 0 18px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
.remark-card {
  margin-top: 12px;
}
</style> 